package org.ronghao.androidwifiplatfrom.activity;

import java.util.ArrayList;
import java.util.List;

import org.ronghao.androidwifiplatfrom.Facade;
import org.ronghao.androidwifiplatfrom.R;
import org.ronghao.androidwifiplatfrom.entity.Game;
import org.ronghao.androidwifiplatfrom.entity.MessageQueue;
import org.ronghao.androidwifiplatfrom.entity.User;
import org.ronghao.androidwifiplatfrom.socket.AndroidServer;
import org.ronghao.androidwifiplatfrom.socket.SocketClient;
import org.ronghao.androidwifiplatfrom.utils.AndroidUtil;
import org.ronghao.androidwifiplatfrom.utils.Contants;
import org.ronghao.androidwifiplatfrom.utils.MessageUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class GameWaitActivity extends Activity implements IUpdateData {
	private ListView users_listview;
	private List<User> mUsers;
	private Game mGame;
	private UserAdapter mUserAdapter;
	private AndroidServer mAndroidServer;
	private Facade mFacade;
	private SocketClient mSocketClient;
	private boolean isCreater;//是否是创建者

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gamewait);

		initData();
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Bundle bundle = getIntent().getExtras();
		mGame = (Game) MessageUtils.getData(Game.class,
				bundle.getString(Contants.COMMUNICATION_GAME));
		isCreater = bundle.getBoolean(Contants.COMMUNICATION_GAME_HOST);
		if (isCreater) {
			if (mGame == null && mGame.getId() <= 0) {
				Toast.makeText(this, "创建失败", Toast.LENGTH_SHORT).show();
				finish();
			}
		} else {
			if (mGame == null && mGame.getId() <= 0) {
				Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
				finish();
			} else {
				Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
			}
		}

		Login();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ExitDialog(GameWaitActivity.this).show();
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 提示退出系统
	 * 
	 * @param context
	 * @return
	 */
	private Dialog ExitDialog(Context context) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("系统信息");
		builder.setMessage("确定要退出游戏吗?");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				SocketClient socketClient = mFacade.createSocketClient(Contants.MSG_UPDATE,
						Contants.MSG_ACTION_LOGOUT,
						MessageUtils.setData(mFacade.getLocalUser()));
				socketClient.start();
				while (socketClient.isAlive()) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				finish();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		return builder.create();
	}

	@Override
	protected void onDestroy() {
		mAndroidServer.setStart(false);
		mAndroidServer.close();
		mAndroidServer = null;
		super.onDestroy();
	}

	/**
	 * 初始化界面
	 * 
	 * @author ronghao
	 * @data 2012-11-27 下午3:34:18
	 */
	private void initData() {
		mUsers = new ArrayList<User>();
		mFacade = new Facade(getApplicationContext());
		mAndroidServer = new AndroidServer(this);
		mAndroidServer.start();

	}

	private void initView() {
		users_listview = (ListView) findViewById(R.id.gamewait_users_listview);
		mUserAdapter = new UserAdapter(this, mUsers);
		users_listview.setAdapter(mUserAdapter);
	}

	/**
	 * 登录
	 * 
	 * @author ronghao
	 * @data 2012-11-22 上午10:58:24
	 */
	private void Login() {
		// TODO:delete
		// mSocketClient = mFacade.createSocketClient(Contants.MSG_UPDATE,
		// Contants.MSG_ACTION_LOGIN, mFacade.getLocalUser()
		// .userToString());

		mFacade.updatarIp();
		mSocketClient = mFacade.createSocketClient(Contants.MSG_UPDATE,
				Contants.MSG_ACTION_LOGIN,
				MessageUtils.setData(mFacade.getLocalUser()));

		// mSocketClient = new SocketClient(Wifi.getInstance(
		// getApplicationContext()).getDHCPIP(), new MessageQueue(
		// 0, Wifi.getInstance(getApplicationContext())
		// .getIpAddress(), "23", Contants.MSG_UPDATE,
		// Contants.MSG_ACTION_LOGIN,
		// editText2.getText().toString()).getString());
		mSocketClient.start();
	}

	class UserAdapter extends BaseAdapter {

		private Context mContext;
		private List<User> mUsers;

		public void setmUsers(List<User> mUsers) {
			this.mUsers = mUsers;
		}

		public UserAdapter(Context context, List<User> users) {
			mContext = context;
			mUsers = users;
		}

		@Override
		public int getCount() {
			return mUsers == null ? 0 : mUsers.size();
		}

		@Override
		public Object getItem(int position) {
			return mUsers == null ? null : mUsers.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getView(int, android.view.View,
		 * android.view.ViewGroup)
		 */
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = new UserView(mContext, mUsers.get(position));
			} else {
				convertView = (UserView) convertView;
				((UserView) convertView).setUser(mUsers.get(position));
			}

			((UserView) convertView).refreshView();
			if (mUsers.get(position).getIp() == mFacade.getLocalUser().getIp()) {
				((UserView) convertView).userName.setText("本机");
			}
			return convertView;
		}

		class UserView extends BaseView {

			private TextView userName;
			private ImageView userPic;
			private User user;

			public void setUser(User user) {
				this.user = user;
			}

			public UserView(Context context, User user) {
				super(context);
				this.user = user;
				setContentView(R.layout.user_item);
			}

			@Override
			public void onLoad() {

			}

			@Override
			public void onRealse() {

			}

			@Override
			public void onDestory() {

			}

			@Override
			public void initView(View view) {
				userPic = (ImageView) view
						.findViewById(R.id.useritem_pic_imageview);
				userName = (TextView) view
						.findViewById(R.id.useritem_username_textview);
				userPic.setBackgroundResource(AndroidUtil
						.getPic(Contants.USERPIC + user.getPic()));
				userName.setText(user.getName());
			}

			public void refreshView() {
				userPic.setBackgroundResource(AndroidUtil
						.getPic(Contants.USERPIC + user.getPic()));
				userName.setText(user.getIp());
			}
		}
	}

	@Override
	public void setData(String msg) {
		Message message = new Message();
		MessageQueue messageQueue = (MessageQueue) MessageUtils.getData(
				MessageQueue.class, msg);
		// MessageQueue messageQueue = MessageQueue.createMessageQueue(msg);
		// TODO:delete
		mFacade.handleMsg(messageQueue);
		message.what = messageQueue.getType();
		Bundle bundle = new Bundle();
		bundle.putString(Contants.COMMUNICATION_DATA, msg);
		bundle.putString(Contants.COMMUNICATION_MSG_DATA,
				messageQueue.getMsgData());
		message.setData(bundle);
		mHandler.sendMessage(message);

		// User user = new User(messageQueue.getMsgData());
		// mUsers.add(user);
		// mUserAdapter.setmUsers(mUsers);
		// mUserAdapter.notifyDataSetChanged();
	}

	/**
	 * 更新界面
	 * @author ronghao
	 * @data 2012-11-30    上午9:19:05
	 */
	private void updateUsers() {
		mUsers = mFacade.getUsers();
		mUserAdapter.setmUsers(mUsers);
		mUserAdapter.notifyDataSetChanged();
	}

	private Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {// 此方法在ui线程运行
			switch (msg.what) {
			case Contants.MSG_UPDATE:
				// mFacade.notifyAllClients(msg.getData().getString(
				// Contants.COMMUNICATION_DATA));
				break;
			case Contants.MSG_BROADCAST:
				updateUsers();
				// msg.getData().getString(Contants.COMMUNICATION_MSG_DATA)
				break;
			case Contants.MSG_FAILURE:
				break;
			}
		}
	};

}
